﻿//// <copyright file="PopulateOnly.cs" company="Clever Software">
//// Copyright (c) 2013, 2014 All Right Reserved, http://www.cleversoftware.by
////
//// This source is subject to the Microsoft Permissive License.
//// Please see the License.txt file for more information.
//// All other rights reserved.
////
//// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
//// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// </copyright>
//// <author>Clever Software</author>
//// <email>info@cleversoftware.by</email>
//// <date>2014-02-04</date> 
//// <summary>CleverCMS source code</summary>

//using System;
//using System.Collections.Generic;
//using System.Data;
//using System.Data.Entity;
//using System.Data.Entity.Infrastructure;
//using System.Data.Objects;
//using System.Data.SqlClient;
//using System.IO;
//using System.IO.Compression;
//using System.Linq;
//using System.Reflection;
//using System.Xml;
//using CleverCMS.Common.Entities;
//using CleverCMS.Data.Concrete;

//namespace CleverCMS.Data.Base
//{
//    public class PopulateOnly<T> : IDatabaseInitializer<T> where T : DbContext
//    {
//        public void InitializeDatabase(T context)
//        {
//            ObjectContext objectContext =
//                    ((IObjectContextAdapter)context).ObjectContext;

//            CheckMigration(context);

//            if (context.Database.Exists())
//            {
//                if (!context.Database.CompatibleWithModel(true))
//                {
//                    DeleteExistingTables(objectContext);
//                    CreateTables(objectContext);
//                    CreateMigrationTable(context, objectContext);
//                    SeedDb(context as DataContext);
//                }
//            }
//        }

//        private void SeedDb(DataContext context)
//        {
//            #region CMS feed

//            #region Pages category 
//            var categories = new List<CmsPageCategory>
//            {
//                new CmsPageCategory { Title = "root", CreatedAt = DateTime.Now },
//                new CmsPageCategory { Title = "Default Category", ParentId = 1, CreatedAt = DateTime.Now},
//                new CmsPageCategory { Title = "Some Usefull Category", ParentId = 1, CreatedAt = DateTime.Now},
//            };
//            categories.ForEach(s => context.CmsPageCategories.Add(s));
//            context.SaveChanges();
//            #endregion

//            #region Pages state
//            var statuses = new List<CmsStatus>
//            {
//                new CmsStatus(StatusCode.Draft) { StatusName = "Draft", Description="Draft Page", CreatedAt=DateTime.Now},
//                new CmsStatus(StatusCode.Dropped) { StatusName = "Dropped", Description="Dropped Page", CreatedAt=DateTime.Now},
//                new CmsStatus(StatusCode.Published) { StatusName = "Published", Description="Published Page", CreatedAt=DateTime.Now}
//            };
//            statuses.ForEach(s => context.Statuses.Add(s));
//            context.SaveChanges();
//            #endregion

//            #region Menus
//            var menuTypes = new List<CmsMenuType>
//            {
//                new CmsMenuType() { Title = "Menu", Type="SideMenu", Description="Left Menu", CreatedAt=DateTime.Now},
//                new CmsMenuType() { Title = "Menu", Type="FooterMenu", Description="Footer Menu", CreatedAt=DateTime.Now},
//                new CmsMenuType() { Title = "Menu", Type="TopMenu", Description="Top Menu", CreatedAt=DateTime.Now},    
//                new CmsMenuType() { Title = "Menu", Type="LeftMenu", Description="Left Menu", CreatedAt=DateTime.Now}
//            };
//            menuTypes.ForEach(s => context.CmsMenuTypes.Add(s));
//            context.SaveChanges();
//            #endregion

//            #region Pages
//            var pages = new List<CmsPage>
//            {
//                new CmsPage
//                {
//                    CategoryId = 2,
//                    Alias = "main",
//                    MetaDescription = "",
//                    MetaKeywords = "",
//                    PageContent = "<h1 style='text-align: center;'>Welcome to the CleverCMS!</h1><p style='text-align: center;'><img style='text-align: center;' src='http://cleversoftware.by/images/product box_small.jpg' alt='' width='200' height='202'></p>",
//                    StatusId = (int) StatusCode.Published,
//                    PageTitle = "Welcome",
//                    SeoTitle = "Welcome",
//                    ModifiedAt = DateTime.Now,
//                    CreatedAt = DateTime.Now
//                },
//                new CmsPage
//                {
//                    CategoryId = 2,
//                    Alias = "about1",
//                    MetaDescription = "",
//                    MetaKeywords = "",
//                    PageContent = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sed quam a nulla ornare semper. Fusce ultrices blandit ligula, sed euismod mauris auctor sed. Pellentesque metus metus, vehicula at mi vitae, sodales dapibus est. Suspendisse potenti. Duis dignissim libero ac quam luctus porta. Sed placerat arcu vel nunc suscipit hendrerit. Nam suscipit urna nec nunc porta, ut cursus dui facilisis. Nulla facilisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sed quam a nulla ornare semper. Fusce ultrices blandit ligula, sed euismod mauris auctor sed. Pellentesque metus metus, vehicula at mi vitae, sodales dapibus est. Suspendisse potenti. Duis dignissim libero ac quam luctus porta. Sed placerat arcu vel nunc suscipit hendrerit. Nam suscipit urna nec nunc porta, ut cursus dui facilisis. Nulla facilisi.</p>",
//                    StatusId = (int) StatusCode.Published,
//                    PageTitle = "Page with rating",
//                    SeoTitle = "Page with rating",
//                    ModifiedAt = DateTime.Now,
//                    CreatedAt = DateTime.Now,
//                    ShowRating = true
//                },
//                new CmsPage
//                {
//                    CategoryId = 3,
//                    Alias = "main1",
//                    MetaDescription = "",
//                    MetaKeywords = "",
//                    PageContent = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sed quam a nulla ornare semper. Fusce ultrices blandit ligula, sed euismod mauris auctor sed. Pellentesque metus metus, vehicula at mi vitae, sodales dapibus est. Suspendisse potenti. Duis dignissim libero ac quam luctus porta. Sed placerat arcu vel nunc suscipit hendrerit. Nam suscipit urna nec nunc porta, ut cursus dui facilisis. Nulla facilisi.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sed quam a nulla ornare semper. Fusce ultrices blandit ligula, sed euismod mauris auctor sed. Pellentesque metus metus, vehicula at mi vitae, sodales dapibus est. Suspendisse potenti. Duis dignissim libero ac quam luctus porta. Sed placerat arcu vel nunc suscipit hendrerit. Nam suscipit urna nec nunc porta, ut cursus dui facilisis. Nulla facilisi.</p>",
//                    StatusId = (int) StatusCode.Published,
//                    PageTitle = "Page with comment",
//                    SeoTitle = "Page with comment",
//                    ModifiedAt = DateTime.Now,
//                    CreatedAt = DateTime.Now,
//                    ShowRating = true,
//                    HasComments = true
//                }
//            };
//            foreach (var page in pages)
//            {
//                context.CmsPages.Add(page);
//            }
//            context.SaveChanges();
//            #endregion

//            #region MenuItems
//            var menu = new CmsMenuItem { Title = "Home", MenuId = 3, EntryId = null, NavigateUrl = "/", ParentId = null, Visible = true, CreatedAt = DateTime.Now };
//            context.CmsMenuItems.Add(menu);
//            context.SaveChanges();

//            var menu1 = new CmsMenuItem { Title = "Page with Rating", MenuId = 3, EntryId = 2, NavigateUrl = "/", ParentId = null, Visible = true, CreatedAt = DateTime.Now };
//            context.CmsMenuItems.Add(menu1);
//            context.SaveChanges();

//            var menu2 = new CmsMenuItem { Title = "Page with Comments", MenuId = 3, EntryId = 3, NavigateUrl = "/", ParentId = null, Visible = true, CreatedAt = DateTime.Now };
//            context.CmsMenuItems.Add(menu2);
//            context.SaveChanges();

//            var menu3 = new CmsMenuItem { Title = "Blog", MenuId = 3, EntryId = null, NavigateUrl = "/blog", ParentId = null, Visible = true, CreatedAt = DateTime.Now };
//            context.CmsMenuItems.Add(menu3);
//            context.SaveChanges();

//            var menu4 = new CmsMenuItem { Title = "404", MenuId = 3, EntryId = null, NavigateUrl = "/some-nonexisting-page", ParentId = null, Visible = true, CreatedAt = DateTime.Now };
//            context.CmsMenuItems.Add(menu4);
//            context.SaveChanges();

//            var menuItems = new List<CmsMenuItem>
//            {
//                new CmsMenuItem { Title = "Sub Home", MenuId=3, EntryId=pages.FirstOrDefault().Id, NavigateUrl="/", ParentId=menu.Id, Visible=true, CreatedAt=DateTime.Now}               
//            };

//            menuItems.ForEach(s => context.CmsMenuItems.Add(s));
//            context.SaveChanges();
//            #endregion

//            #region Users

//            context.UserProfiles.Add(new UserProfile { CreatedAt = DateTime.Now, DisplayName = "user1", Login = "user1", Email = "user1@mail.ru" });
//            context.SaveChanges();

//            #endregion

//            #region Rating
//            var ratings = new List<CmsRating>
//            {
//                new CmsRating { ObjectId = 2, IsPage = true, IsBlogEntry = false, Rating = 4.75, UserId = 1 },
//                new CmsRating { ObjectId = 3, IsPage = true, IsBlogEntry = false, Rating = 4.75, UserId = 1 } 
//            };
//            ratings.ForEach(x => context.BlogEntryRatings.Add(x));
//            context.SaveChanges();
//            #endregion

//            #endregion

//            #region Blog feed

//            var category1 = new BlogEntryCategory() { Alias = "main", CategoryName = "Main", Picture = "", SortOrder = 0 };
//            context.BlogEntryCategories.Add(category1);

//            var category2 = new BlogEntryCategory() { Alias = "public", CategoryName = "Public", Picture = "", SortOrder = 0 };
//            context.BlogEntryCategories.Add(category2);

//            var category3 = new BlogEntryCategory() { Alias = "news", CategoryName = "News", Picture = "", SortOrder = 0 };
//            context.BlogEntryCategories.Add(category3);
//            context.SaveChanges();

//            #region Posts 
//            var cts = context.BlogEntryCategories.ToList();
//            for (int i = 1; i <= cts.Count; i++)
//            {
//                context.BlogEntries.Add(new BlogEntry
//                {
//                    Created = DateTime.Now,
//                    CategoryId = i,
//                    Header = "Some" + i,
//                    HeaderUrl = "some-" + i,
//                    ShortContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tempus dapibus nisl sit amet imperdiet. In hac habitasse platea dictumst. Suspendisse gravida ante nisi, sit amet volutpat augue aliquam non. Nulla sit amet velit faucibus, consectetur magna eu, feugiat augue. Maecenas in consequat lacus. Nulla placerat risus risus, mattis volutpat nisi accumsan at. Morbi imperdiet ultrices nunc sed consequat. Morbi blandit nisi nisi, ut aliquam orci posuere non. In hac habitasse platea dictumst. In eros risus, sodales quis luctus sed, sagittis quis mauris. Maecenas a felis enim. Etiam ac tempus justo.Pellentesque tincidunt posuere pretium. Integer eu augue sem. Pellentesque eget metus at nisi mattis elementum. Nunc erat sapien, eleifend quis est ut, pretium mattis nunc. Fusce vitae accumsan risus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus bibendum risus dui, vitae fermentum magna imperdiet quis. Donec ornare ipsum quis nibh vestibulum, nec dignissim dolor egestas. Nunc rutrum condimentum egestas. Etiam porta congue lectus eu facilisis.",
//                    Content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tempus dapibus nisl sit amet imperdiet. In hac habitasse platea dictumst. Suspendisse gravida ante nisi, sit amet volutpat augue aliquam non. Nulla sit amet velit faucibus, consectetur magna eu, feugiat augue. Maecenas in consequat lacus. Nulla placerat risus risus, mattis volutpat nisi accumsan at. Morbi imperdiet ultrices nunc sed consequat. Morbi blandit nisi nisi, ut aliquam orci posuere non. In hac habitasse platea dictumst. In eros risus, sodales quis luctus sed, sagittis quis mauris. Maecenas a felis enim. Etiam ac tempus justo.Pellentesque tincidunt posuere pretium. Integer eu augue sem. Pellentesque eget metus at nisi mattis elementum. Nunc erat sapien, eleifend quis est ut, pretium mattis nunc. Fusce vitae accumsan risus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus bibendum risus dui, vitae fermentum magna imperdiet quis. Donec ornare ipsum quis nibh vestibulum, nec dignissim dolor egestas. Nunc rutrum condimentum egestas. Etiam porta congue lectus eu facilisis.",
//                    SeoTitle = "Some",
//                    MetaDescription = "Some",
//                    MetaKeywords = "Some",
//                    Visible = true,
//                    ShowRating = true,
//                    Alias = "some-" + i,
//                    Published = DateTime.Now,
//                    ViewCount = 0
//                });
//                context.SaveChanges();

//                context.BlogEntryRatings.Add(new CmsRating
//                {
//                    ObjectId = i,
//                    IsPage = false,
//                    IsBlogEntry = true,
//                    UserId = 1,
//                    Rating = 4.75
//                });
//                context.SaveChanges();
//            }
//            context.SaveChanges();
//            #endregion

//            #endregion
//        }

//        #region Re-create tables

//        private void DeleteExistingTables(ObjectContext objectContext)
//        {
//            objectContext.ExecuteStoreCommand(DeleteAllTablesWithMigrationTable);
//        }

//        private void DeleteExistingTablesWithoutMigration(ObjectContext objectContext) 
//        {
//            objectContext.ExecuteStoreCommand(Deletealltablesscript);
//        }

//        private void CreateTables(ObjectContext objectContext)
//        {
//            string dataBaseCreateScript =
//                objectContext.CreateDatabaseScript();
//            objectContext.ExecuteStoreCommand(dataBaseCreateScript);
//        }

//        #endregion

//        #region Check and Create if it want _MigrationHistory table

//        private void CheckMigration(T context)
//        {
//            ObjectContext objectContext =
//                    ((IObjectContextAdapter)context).ObjectContext;

//            var result = objectContext.ExecuteStoreQuery<int>("select Count(*) from INFORMATION_SCHEMA.TABLES where TABLE_NAME = '__MigrationHistory'");
//            int i = result.FirstOrDefault();

//            if (i == 0)
//            {
//                CreateMigrationTable(context, objectContext);
//                DeleteExistingTablesWithoutMigration(objectContext);
//                CreateTables(objectContext);
//                SeedDb(context as DataContext);
//            }
//        }

//        private void CreateMigrationTable(T context, ObjectContext objectContext)
//        {
//            var modelParam = new SqlParameter("model", SqlDbType.VarBinary);
//            modelParam.Value = GetModel(context);
//            var versionParam = new SqlParameter("version", SqlDbType.NVarChar);
//            versionParam.Value = GetProductVersion();
//            objectContext.ExecuteStoreCommand(CreateMigrationTableScript, modelParam, versionParam);
//            objectContext.SaveChanges();
//        }

//        private byte[] GetModel(T context)
//        {
//            using (var memoryStream = new MemoryStream())
//            {
//                using (var gzipStream = new GZipStream(
//                    memoryStream,
//                    CompressionMode.Compress))
//                using (var xmlWriter = XmlWriter.Create(
//                    gzipStream,
//                    new XmlWriterSettings { Indent = true }))
//                {
//                    EdmxWriter.WriteEdmx(context, xmlWriter);
//                }

//                return memoryStream.ToArray();
//            }
//        }

//        private string GetProductVersion()
//        {
//            return typeof(DbContext).Assembly
//                .GetCustomAttributes(false)
//                .OfType<AssemblyInformationalVersionAttribute>()
//                .Single()
//                .InformationalVersion;
//        }

//        #endregion

//        private const string Deletealltablesscript =
//            @"while(exists(SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='FOREIGN KEY' ))
//            begin
//	            declare @sql nvarchar(2000)
//	            SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME
//	            + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
//	            FROM information_schema.table_constraints
//	            WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME != '__MigrationHistory'
//	            exec (@sql)
//            end
//            declare @cmd varchar(4000)
//            declare cmds cursor for 
//            Select
//                'DROP TABLE [' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'
//            From
//                INFORMATION_SCHEMA.TABLES
//            Where 
//                TABLE_NAME != '__MigrationHistory'
//            open cmds
//            while 1=1
//            begin
//                fetch cmds into @cmd
//                if @@fetch_status != 0 break
//                print @cmd
//                exec(@cmd)
//            end
//            close cmds
//            deallocate cmds";

//        private const string DeleteAllTablesWithMigrationTable = @"while(exists(SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='FOREIGN KEY' ))
//            begin
//	            declare @sql nvarchar(2000)
//	            SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME 
//	            + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
//	            FROM information_schema.table_constraints
//	            WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
//	            exec (@sql)
//            end
//            declare @cmd varchar(4000)
//            declare cmds cursor for 
//            Select
//                'DROP TABLE [' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'
//            From
//                INFORMATION_SCHEMA.TABLES
//            open cmds
//            while 1=1
//            begin
//                fetch cmds into @cmd
//                if @@fetch_status != 0 break
//                print @cmd
//                exec(@cmd)
//            end
//            close cmds
//            deallocate cmds";

//        private const string CreateMigrationTableScript =
//            @"CREATE TABLE [dbo].[__MigrationHistory] (
//            MigrationId NVARCHAR(100) NOT NULL,
//            Model VARBINARY(MAX) NOT NULL,
//            ProductVersion NVARCHAR(100) NOT NULL);
// 
//            ALTER TABLE __MigrationHistory
//            ADD PRIMARY KEY (MigrationId);
// 
//            INSERT INTO __MigrationHistory (
//                MigrationId,
//                Model,
//                ProductVersion)
//            VALUES ('InitialCreate', @model, @version);";

//        protected virtual void Seed(T context) { }
//    }
//}